package secondriver.springsubway.example.rpv.validator;

import net.sf.oval.configuration.xml.XMLConfigurer;
import net.sf.oval.guard.Guard;
import secondriver.springsubway.example.rpv.ParameterValidator;

import java.io.File;
import java.io.IOException;

/**
 * Created by ZhangXiao on 2015/6/12.
 */
public class ConfigureParameterValidator extends AbstractParameterValidator {

    private static ConfigureParameterValidator instance;
    private String validatorConfig = DEFAULT_VALIDATOR_CONFIG;

    public synchronized static ParameterValidator instance() {
        if (null != instance) {
            instance = new ConfigureParameterValidator();
            instance.setMessageBaseName(DEFAULT_MESSAGE_BASENAME);
            instance.setValidatorConfig(DEFAULT_VALIDATOR_CONFIG);
        }
        return instance;
    }

    @Override
    public void initGuard() {
        if (null == validatorConfig) {
            throw new IllegalArgumentException("validator configure file not set.");
        }
        ClassLoader classLoader = getClass().getClassLoader();
        String path = classLoader.getResource("/").getPath() + validatorConfig;
        File file = new File(path);
        try {
            XMLConfigurer xmlConfigurer = new XMLConfigurer(file);
            guard = new Guard(xmlConfigurer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getValidatorConfig() {
        return validatorConfig;
    }

    public void setValidatorConfig(String validatorConfig) {
        this.validatorConfig = validatorConfig;
    }
}
